package com.sharemarking.system.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 用于记录登录失败次数
 * @author song
 *
 */
@Component
public class AuthenticationFailureListenerImpl implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {

	public static final String loginFailTimesCacheName="LOGIN_FAILURE_TIMES";
	public static final String remoteLoginFailureTimesCacheName="REMOTE_LOGIN_FAILURE_TIMES";
	
	@Autowired
	private CacheManager cm;
	
	@Autowired
	private HttpServletRequest request;
	
	@Override
	public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
		String username=(String)event.getAuthentication().getPrincipal();
		String xRealIp=request.getHeader("X-real-ip");
		Cache c=cm.getCache(loginFailTimesCacheName);
		ValueWrapper vw=c.get(username);
		Integer count=vw==null?0:(Integer)vw.get();
		c.put(username, count+1);
		Cache remoteAccessCache=cm.getCache(remoteLoginFailureTimesCacheName);
		Integer remoteAccessCount=null;
		synchronized (this) {
			ValueWrapper remoteAccessVw=remoteAccessCache.get(xRealIp);
			remoteAccessCount=remoteAccessVw==null?0:(Integer)remoteAccessVw.get();
			remoteAccessCache.put(xRealIp, remoteAccessCount+1);
		}
		//if(count>3) throw new LockedException("User account is locked");
	}

}
